package com.list88zhu.android.sunflower.algorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/21
 */
public class ThreadExample {

    private static final int MAX_QUEUE_SIZE = 5;

    public static void main(String[] args) {
        final Queue<Integer> sharedQueue = new LinkedList<>();
        Thread producer = new Producer(sharedQueue);
        Thread consumer = new Consumer(sharedQueue);
        producer.start();
        consumer.start();
    }


    public static class Producer extends Thread {

        private final Queue<Integer> sharedQueue;

        public Producer(Queue queue) {
            super();
            this.sharedQueue = queue;
        }

        @Override
        public void run() {
            for(int i = 0; i < 100; i++) {
                synchronized (sharedQueue) {
                    while (sharedQueue.size() >= MAX_QUEUE_SIZE) {
                        System.out.println("队列已满，等待消费");
                        try {
                            sharedQueue.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    sharedQueue.add(i);
                    System.out.println("进行生成：" + i);
                    sharedQueue.notify();
                }
            }
        }
    }


    public static class Consumer extends Thread{
        private final Queue<Integer> sharedQueue;
        public Consumer(Queue queue){
            super();
            this.sharedQueue = queue;
        }

        @Override
        public void run() {
            while(true) {
                synchronized (sharedQueue) {
                    while (sharedQueue.size() <= 0) {
                        try {
                            System.out.println("以消费完，等待生产");
                            sharedQueue.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    int number = sharedQueue.poll();
                    System.out.println("进行消费："+number);
                    sharedQueue.notify();
                }
            }
        }
    }
}
